package com.xinghen.common.util;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.Properties;

/**
 * @author xinghen
 * @ClassName: VelocityUtils
 * @Package: com.xinghen.common.util
 * @Description TODO
 * @create 2017-12-06 15:38
 */
public class VelocityUtils {


    public static void generate(VelocityContext context, String templateFile, String outputPath) {
        try {
            Properties properties = new Properties();
            properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, new File(templateFile).getParent());
            Velocity.init(properties);
            Template template = Velocity.getTemplate(new File(templateFile).getName(), "utf-8");
            BufferedWriter writer = Files.newWriter(new File(outputPath), Charsets.UTF_8);
            template.merge(context, writer);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
